package com.cdtye.shuoh.config.mqtt;

import com.cdtye.shuoh.domain.device.entity.DeviceTopic;
import com.cdtye.shuoh.domain.enums.DeviceTopicEnum;
import com.cdtye.shuoh.service.device.DeviceTopicService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 订阅类
 */
@Component
public class MqttSubClient {

    private static final Logger log = LoggerFactory.getLogger(MqttSubClient.class);

    @Autowired
    private DeviceTopicService deviceTopicService;

    public void subScribeDataPublishTopic(String defaultTopic) {
        String mqtt_topic[] = defaultTopic.split(",");
        for (int i = 0; i < mqtt_topic.length; i++) {
            subscribe(mqtt_topic[i], 0);//订阅主题
        }
        List<DeviceTopic> topicList=deviceTopicService.findByType(DeviceTopicEnum.CUSTOM.getKey());
        for (DeviceTopic deviceTopic : topicList) {
            if(null!=deviceTopic.getTopic()){
                subscribe(deviceTopic.getTopic(), 0);//订阅主题
            }
        }

    }

    /**
     * 订阅某个主题，qos默认为0
     *
     * @param topic
     */
    public void subscribe(String topic) {
        subscribe(topic, 0);
    }

    /**
     * 订阅某个主题
     *
     * @param topic 主题名
     * @param qos
     */
    public void subscribe(String topic, int qos) {
        try {
            MqttClient client = MqttPushClient.getClient();
            if (client == null) return;
            client.subscribe(topic, qos);
            log.info("订阅主题:{}", topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}


